﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MyBlog.IService;
using MyBlog.Model;
using MyBlog.Model.DTO;
using MyBlog.Utility._MD5;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyBlog.WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class WriteInfoController : ControllerBase
    {
        private readonly IWriteInfoService _writeInfoService;
        public WriteInfoController(IWriteInfoService writeInfoService)
        {
            this._writeInfoService = writeInfoService;
        }

        [HttpPost("Create")]
        public async Task<ApiResult> Create(string name, string username, string userpwd)
        {
            WriteInfo writeInfo = new WriteInfo()
            {
                Name = name,
                UserName = username,
                UserPwd = MD5Helper.MD5Encrypt32(userpwd)
            };

            //判断数据库中是否存在该账户
            var oldWrite = await _writeInfoService.FindAsync(x => x.Name == name);
            if (oldWrite != null)
            {
                return ApiResultHelper.Error("账号已经存在");
            }
            bool b = await _writeInfoService.CreateAsync(writeInfo);
            if (!b) return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success("成功");
        }

        [HttpPut("Edit")]
        public async Task<ApiResult> Edit(string name)
        {
            //获取token中写入的用户Id值
            int id = Convert.ToInt32(this.User.FindFirst("Id").Value);

            var write = await _writeInfoService.FindAsync(id);
            write.Name = name;

            bool b = await _writeInfoService.EditAsync(write);
            if (!b) return ApiResultHelper.Error("修改失败");

            return ApiResultHelper.Success("成功");
        }



        [HttpGet("FindWriterByNoAutoMapper")]
        public async Task<ApiResult> FindWriterByNoAutoMapper(int id)
        {
            var writer = await _writeInfoService.FindAsync(id);
            return ApiResultHelper.Success(writer);
        }

        [HttpGet("FindWriterByAutoMapper")]
        public async Task<ApiResult> FindWriterByAutoMapper([FromServices] IMapper mapper, int id)
        {
            var writer = await _writeInfoService.FindAsync(id);

            var n_writer = mapper.Map<WriteInfoDTO>(writer);

            return ApiResultHelper.Success(n_writer);
        }

    }
}
